/*
 * Author: Yuan Li
 * Title: lab5 for the 15123 summer 
 * Date: Aug 22 2011
 */

#include <stdio.h>
#include <stdlib.h>


/* my own macro */
#define ELEMENTS 16

#define true 1
#define false 0

#define DEBUG true
/********************************/

int main(int argc, char** argv){
	FILE* inFile;
	int element[ELEMENTS];
	int cnt;
	int sum;
	int tmp;
	int index;
	int pattern;
	unsigned short max;
	int setSum;
	unsigned short tmpPattern;

#if DEBUG == true
#endif
	/* Check number of the input */
	if (argc < 2){
		printf("need to specify input file name!\n");
		exit(EXIT_FAILURE);
	}

	/* Open the input file */
	inFile = fopen(argv[argc-1],"rt");
	if (inFile == NULL){
		printf("fail to open %s!\n", argv[argc-1]);
		exit(EXIT_FAILURE);
	}

	/* Read data from input file */
	cnt = 0;
	sum = 0;
	tmp = 0;
	while (fscanf(inFile,"%d",&tmp) == 1){
		if (cnt == ELEMENTS){
			sum = tmp;
			break;
		}

		element[cnt++] = tmp;
	}

	/* Check correction of reading */
	if (cnt != 16){
		printf("did not read enough element\n");
		exit(EXIT_FAILURE);
	}

	/* Print out the input file */
	for (index=0; index < ELEMENTS; index++){
		printf("%d ", element[index]);
	}
	printf("\n%d\n",sum);

	/* Generate all the subset */
	max = ~0;
	setSum = 0;
	tmpPattern = 0;
	for (pattern=0; pattern <= max; pattern++){
		/* map pattern to element array and compute the setSum */
		setSum = 0;
		for (index=0; index < ELEMENTS; index++){
			tmpPattern = ((unsigned short) pattern) >> index;
			if (tmpPattern & ((unsigned short) 1)){
				setSum = setSum + element[index];
			}
			else{
				/* setSum = setSum + 0; */
			}
		}
		/* decide whether this subset is we desired */
		if (setSum == sum){
			/* print out this qualified subset */
			for (index=0; index < ELEMENTS; index++){
				tmpPattern = ((unsigned short) pattern) >> index;
				if (tmpPattern & 1){
					printf("%d ", element[index]);
				}
				else{
					/* omitt this element */
				}
			}
			printf("\n");
		}
		else{
			/* omitt this subset */
		}
	}

	printf("%d",(0xfffe>>0)&1);
	return EXIT_SUCCESS;
}
